<template>
  <el-dialog v-model="accountStore.showChangePasswordDialog"
             class="dialog-shell"
             width="350px"
             :draggable="true"
             @close="handleClose"
             :close-on-click-modal="false"
             style="border-radius: 5px;"
  >
    <template #header>
      <h1>登录发现更多精彩</h1>
      <div class="line"></div>
    </template>

    <template #default>
      <div class="form-shell">
        <span class="info">邮箱重置密码</span>
        <el-form class="form" :model="formData" ref="form" :rules="rules">
          <el-form-item prop="email">
            <el-input placeholder="请输入邮箱" v-model="formData.email">
              <template #prefix>
                <svg class="icon">
                  <use xlink:href="#icon-youxiang"></use>
                </svg>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item type="password" prop="password">
            <el-input placeholder="请输入新密码" show-password type="password" v-model="formData.password">
              <template #prefix>
                <svg class="icon">
                  <use xlink:href="#icon-mima"></use>
                </svg>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input placeholder="请输入验证码" v-model="formData.code">
              <template #prefix>
                <svg class="icon">
                  <use xlink:href="#icon-yanzhengyanzhengma"></use>
                </svg>
              </template>
              <template #suffix>
                <el-button class="getCodeBtn"
                           :disabled="countDown>0"
                           :loading="getCodeBtn.isLoading"
                           @click.stop="getEmailCode($refs.form)">
                  {{ countDown > 0 ? countDown : null }}获取验证码
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <div class="buttons">
            <el-button class="submit-btn" type="primary" @click="onSubmit($refs.form)">提交</el-button>
            <el-button class="toLogin-btn" @click="toLogin">返回登录</el-button>
          </div>
        </el-form>
      </div>

    </template>
  </el-dialog>

</template>

<script setup>
import {reactive, ref} from 'vue'
import {changePasswordApi, checkEmailApi, registerApi} from "@/api/loginApi.js";
import {getEmailCaptchaApi} from "@/api/captchaApi.js";
import {useAccountStore} from "@/store/accountStore.js";
import {ElMessage} from "element-plus";

const accountStore = useAccountStore();
let getCodeBtn = ref({
  isLoading: false,
  disabled: false
})
// 表单数据
let formData = ref({
  email: '',
  password: '',
  code: '',
})

/**
 * 提交表单
 */
const onSubmit = async (form) => {
  await form.validate() //表单校验
  let response = await changePasswordApi(formData.value);
  ElMessage.success('修改成功')
  await accountStore.logout() //退出登录
  accountStore.showChangePasswordDialog = false
}

/**
 * 获取验证码
 * @returns {Promise<void>}
 */
const getEmailCode = async (form) => {
  await form.validateField('email')
  try {
    getCodeBtn.value.isLoading = true
    let response = await getEmailCaptchaApi(formData.value.email, 1);
    ElMessage.success('验证码发送成功，请查看邮箱')
    limitGetEmailCode()
  } finally {
    getCodeBtn.value.isLoading = false
  }

}
/**
 * 获取邮箱验证码限制
 */
let countDown = ref(0)
const limitGetEmailCode = () => {
  countDown.value = 30
  let id = setInterval(function () {
    if (countDown.value <= 0) {
      clearInterval(id)
      return
    }
    countDown.value -= 1
  }, 1000)
}


/**
 * 邮箱格式检验
 */
const emailValidator = (rule, value, callback) => {
  // 邮箱格式校验
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (!emailReg.test(value)) {
    return callback(new Error('邮箱格式错误'))
  }
  // 验证邮箱是否注册
  checkEmailApi(value).then(res=>{
    if (res.code !== 200){
      return callback(new Error("账号不存在"))
    }
    return callback()
  })

}

/**
 * 表单校验规则
 */
const rules = reactive({
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {validator: emailValidator,trigger: 'blur'},
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {min: 6, max: 20, message: "密码应为6-20位字符", trigger: 'blur'},
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
  ]
})

/**
 * 返回登录弹窗
 */
function toLogin(){
  accountStore.showChangePasswordDialog = false
  accountStore.showLoginDialog = true
}
/**
 * 修改密码弹窗关闭时的回调
 */
function handleClose() {
  formData.value = {email: '', password: '', code: ''}
}
</script>

<style lang="scss" scoped>
.dialog-shell {
  h1 {
    font-size: 1.2rem;
  }

  .line {
    width: 100%;
    position: relative;
    top: 1rem;
    border-bottom: 1px solid rgba(99, 99, 99, 0.2);
  }

}

.form-shell {
  .info {
    font-size: 1rem;
    position: relative;
    top: -0.5rem;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
    background-color: #f2f3f5;
    height: 2.5rem;
  }

  :deep(.el-input__wrapper:has(.el-input__inner:focus)) {
    box-shadow: 0 0 0 1px #409eff inset;
    background-color: transparent;
  }

  .getCodeBtn {
    background-color: transparent;
    border: none;
  }

  .buttons {
    display: flex;
    flex-direction: column;
    align-items: center;

    .submit-btn {
      width: 100%;
      height: 2.5rem;
    }

    .toLogin-btn {
      position: relative;
      border: none;
      top: 1rem;
      background-color: transparent;
    }
  }

}

</style>